#!/bin/bash

# 完整的证书管理脚本
# 适用于 macOS 系统

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_highlight() {
    echo -e "${PURPLE}[HIGHLIGHT]${NC} $1"
}

CERT_FILE="ssl/smartinput.crt"
CERT_NAME="192.168.137.122"

# 显示帮助信息
show_help() {
    echo "证书管理脚本"
    echo ""
    echo "用法: $0 [命令]"
    echo ""
    echo "命令:"
    echo "  status    显示证书状态"
    echo "  import    导入证书到钥匙串"
    echo "  trust     设置证书信任状态"
    echo "  test      测试证书连接"
    echo "  remove    删除证书"
    echo "  help      显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 status"
    echo "  $0 import"
    echo "  $0 trust"
}

# 检查证书文件
check_cert_file() {
    if [ ! -f "$CERT_FILE" ]; then
        log_error "找不到证书文件: $CERT_FILE"
        return 1
    fi
    log_success "找到证书文件: $CERT_FILE"
    return 0
}

# 显示证书状态
show_status() {
    echo "=== 证书状态检查 ==="
    
    if ! check_cert_file; then
        return 1
    fi
    
    echo ""
    echo "证书信息:"
    openssl x509 -in "$CERT_FILE" -text -noout | grep -A 5 "Subject Alternative Name"
    
    echo ""
    echo "登录钥匙串状态:"
    if security find-certificate -c "$CERT_NAME" ~/Library/Keychains/login.keychain-db > /dev/null 2>&1; then
        log_success "证书存在于登录钥匙串"
    else
        log_warning "证书不存在于登录钥匙串"
    fi
    
    echo ""
    echo "系统钥匙串状态:"
    if security find-certificate -c "$CERT_NAME" /Library/Keychains/System.keychain > /dev/null 2>&1; then
        log_success "证书存在于系统钥匙串"
    else
        log_warning "证书不存在于系统钥匙串"
    fi
    
    echo ""
    echo "信任状态:"
    if security find-trust-settings -d "$CERT_NAME" ~/Library/Keychains/login.keychain-db > /dev/null 2>&1; then
        log_success "证书已设置为信任状态"
    else
        log_warning "证书未设置为信任状态"
    fi
}

# 导入证书
import_cert() {
    echo "=== 导入证书 ==="
    
    if ! check_cert_file; then
        return 1
    fi
    
    echo ""
    log_info "导入证书到登录钥匙串..."
    if security import "$CERT_FILE" -k ~/Library/Keychains/login.keychain-db; then
        log_success "证书已导入到登录钥匙串"
    else
        log_warning "证书可能已存在或导入失败"
    fi
    
    echo ""
    log_info "导入证书到系统钥匙串..."
    if sudo security import "$CERT_FILE" -k /Library/Keychains/System.keychain; then
        log_success "证书已导入到系统钥匙串"
    else
        log_warning "系统钥匙串导入失败或需要管理员权限"
    fi
}

# 设置信任状态
trust_cert() {
    echo "=== 设置证书信任状态 ==="
    
    if ! check_cert_file; then
        return 1
    fi
    
    echo ""
    log_info "设置登录钥匙串信任状态..."
    if security add-trusted-cert -d -r trustRoot -k ~/Library/Keychains/login.keychain-db "$CERT_FILE"; then
        log_success "登录钥匙串信任状态设置成功"
    else
        log_warning "登录钥匙串信任状态设置失败，可能需要手动设置"
    fi
    
    echo ""
    log_info "设置系统钥匙串信任状态..."
    if sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "$CERT_FILE"; then
        log_success "系统钥匙串信任状态设置成功"
    else
        log_warning "系统钥匙串信任状态设置失败，可能需要手动设置"
    fi
    
    echo ""
    log_highlight "如果自动设置失败，请手动设置信任状态："
    echo "1. 打开 '钥匙串访问' 应用"
    echo "2. 选择 '登录' 钥匙串"
    echo "3. 搜索 '$CERT_NAME'"
    echo "4. 双击证书，设置 '使用此证书时' 为 '始终信任'"
}

# 测试证书连接
test_cert() {
    echo "=== 测试证书连接 ==="
    
    if ! check_cert_file; then
        return 1
    fi
    
    echo ""
    log_info "测试 HTTPS 连接（忽略证书验证）:"
    if curl -k -s -I https://192.168.137.122/api/auth/test > /dev/null; then
        log_success "HTTPS 连接正常"
    else
        log_error "HTTPS 连接失败"
    fi
    
    echo ""
    log_info "测试 HTTPS 连接（验证证书）:"
    if curl -s -I https://192.168.137.122/api/auth/test > /dev/null; then
        log_success "证书验证通过"
    else
        log_warning "证书验证失败，需要设置信任状态"
    fi
    
    echo ""
    log_info "测试 API 连接:"
    if curl -k -s https://192.168.137.122/api/auth/test | grep -q "success"; then
        log_success "API 连接正常"
    else
        log_error "API 连接失败"
    fi
}

# 删除证书
remove_cert() {
    echo "=== 删除证书 ==="
    
    echo ""
    log_info "删除登录钥匙串中的证书..."
    if security delete-certificate -c "$CERT_NAME" ~/Library/Keychains/login.keychain-db; then
        log_success "登录钥匙串中的证书已删除"
    else
        log_warning "登录钥匙串中未找到证书或删除失败"
    fi
    
    echo ""
    log_info "删除系统钥匙串中的证书..."
    if sudo security delete-certificate -c "$CERT_NAME" /Library/Keychains/System.keychain; then
        log_success "系统钥匙串中的证书已删除"
    else
        log_warning "系统钥匙串中未找到证书或删除失败"
    fi
}

# 主函数
main() {
    case "${1:-help}" in
        status)
            show_status
            ;;
        import)
            import_cert
            ;;
        trust)
            trust_cert
            ;;
        test)
            test_cert
            ;;
        remove)
            remove_cert
            ;;
        help|*)
            show_help
            ;;
    esac
}

# 运行主函数
main "$@" 